package cn.elegent.tx.feign;

import cn.elegent.ac.context.ElegentACContext;
import cn.elegent.ac.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * AuthInterceptor
 * @author:
 * @describe: 权限拦截器
 * @date:
 **/
@Slf4j
public class ACTXInterceptor implements HandlerInterceptor {


    /**
     * 进入controller层之前拦截请求
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String chain_id = request.getHeader(ElegentACTXConstant.CHAINID_HEAD);    //获取链路id

        if(chain_id==null){
            chain_id = UUIDUtils.getUUID();
        }
        log.info("链路id:{} ",chain_id);

        ElegentACContext.set(chain_id );

        return true;
    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     *
     * 请求之后，控制器中抛出了异常的话就不会执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //ElegentACContext.remove();
    }

    /**
     * 视图渲染之后的操作
     *
     * 请求之后调用，不管抛不抛出异常都会被调用.参数中异常如果被异常处理器调用的话就不会传入到参数中．
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //ElegentACContext.remove();
    }
}